def gprint(grid):
    for row in grid:
        print(*row)


class Solution:
    def islandPerimeter(self, grid: list[list[int]]) -> int:
        # Barier method
        island_width = len(grid[0])
        island_height = len(grid)

        grid = [[0] + row + [0] for row in grid]

        grid.insert(0, [0] * (island_width + 2))
        grid.append([0] * (island_width + 2))

        perimeter = 0

        for i in range(1, island_height + 1):
            for j in range(1, island_width + 1):
                if grid[i][j] == 0:
                    continue
                if grid[i-1][j] == 0:
                    perimeter += 1
                if grid[i][j-1] == 0:
                    perimeter += 1
                if grid[i+1][j] == 0:
                    perimeter += 1
                if grid[i][j+1] == 0:
                    perimeter += 1

        return perimeter
